package com.cd.controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.cd.bean.Product;
import com.cd.service.product.ProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 产品展示
 *@Author zhk qq1003589522
 *@Date 2018-1-5
 **/
@RequestMapping("/pro")
@Controller
public class ProductController {

	@Autowired
	ProductService productService;
	
	
	/**
	 * 查询列表（带分页）
	 * @param pn
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/listpro")
	public ModelAndView listWithPages(@RequestParam(value = "pn",defaultValue="1")Integer pn) throws Exception {
		ModelAndView mv = new ModelAndView();
		PageHelper.startPage(pn, 16);//开始分页
	    List<Product> list = productService.listAll();
		PageInfo page = new PageInfo(list,5);//设置分页信息
		mv.addObject("pageInfo", page);
		mv.setViewName("info/cpzs/cpzs");
		return mv;
	}
	/**
	 * 根据id查询
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findById")
	public ModelAndView findById(@RequestParam(value = "id") Integer id) throws Exception {
		ModelAndView mv = new ModelAndView();
		Product pro = null;
		Product prepro = null;
		Product nextpro = null;
		int total = productService.size();//获取总记录
		int nextId = id+1;
		int preId = id-1;
		if(id <= total){
			if(id >= 1){
				pro = productService.findById(id);//当前条
				prepro = productService.findById(preId);//前一条
				nextpro = productService.findById(nextId);//下一条	
			}else {
				pro = productService.findById(id+1);
			}
		}else{
			pro = productService.findById(id-1);
		}
		
		mv.addObject("pro", pro);
		mv.addObject("prepro", prepro);
		mv.addObject("nextpro", nextpro);
		mv.setViewName("info/cpzs/cpzs_show");
		return mv;
	}
	

	/**
	 * 后台显示产品列表 
	 * @param pn
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(value = "pn",defaultValue="1")Integer pn) throws Exception {
		ModelAndView mv = new ModelAndView();
		PageHelper.startPage(pn, 10);//开始分页,每页10条记录
	    List<Product> list = productService.listAll();
		PageInfo page = new PageInfo(list,5);//设置分页信息
		mv.addObject("pageInfo", page);
		mv.setViewName("admin/cpgl/product_list");
		return mv;
	}
	
	
	/**
	 * 修改
	 * @param id
	 * @param title
	 * @param content
	 * @param level
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/edit")
	public ModelAndView eidt(@RequestParam(value="PRODUCT_ID")Integer id,
			                 @RequestParam(value="PRODUCT_NAME")String name,
			                 @RequestParam(value="PRODUCT_CONTENT")String content) throws Exception {
			ModelAndView mv = new ModelAndView();
			Product product = productService.findById(id);
			product.setPRODUCT_NAME(name);
			product.setPRODUCT_CONTENT(content);
			product.setMODIFY_TIME(new Date());
			productService.edit(product);
			mv.setViewName("redirect:list.do");
		return mv;
	}
	
	/**
	 * 去查看产品内容页面
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/goContent")
	public ModelAndView goContent(@RequestParam(value="id")Integer id) throws Exception {
		ModelAndView mv = new ModelAndView();
		Product product = productService.findById(id);
		//System.out.println(news.getNEWS_ID());
		mv.addObject("product", product);
		mv.setViewName("admin/cpgl/product_content");
		return mv;
	}
	/**
	 * 去查看产品图片
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/goImg")
	public ModelAndView goIMG(@RequestParam(value="id")Integer id) throws Exception {
		ModelAndView mv = new ModelAndView();
		Product product = productService.findById(id);
		//System.out.println(news.getNEWS_ID());
		mv.addObject("product", product);
		mv.setViewName("admin/cpgl/product_content");
		return mv;
	}
	/**
	 * 去编辑界面
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/goEdit")
	public ModelAndView goEdit(@RequestParam(value="id")Integer id) throws Exception {
		ModelAndView mv = new ModelAndView();
		Product product = productService.findById(id);
		mv.addObject("product", product);
		mv.setViewName("admin/cpgl/product_edit");
		return mv;
	}
	
	
	/**
	 * 去新增页面
	 * @return
	 */
	@RequestMapping("/goAdd")
	public ModelAndView saveView(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("admin/cpgl/product_add");
		return mv;
	}
	
	/**
	 * 新增
	 * @param id
	 * @param name
	 * @param content
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public ModelAndView save(
							 @RequestParam(value="PRODUCT_NAME")String name,
							 @RequestParam(value="PRODUCT_CONTENT")String content,HttpServletRequest request,
							 @RequestParam("file") MultipartFile file) throws Exception {
		String persistFileUrl = null;
		 //如果文件不为空，写入上传路径
		if(!file.isEmpty()) {
			//上传文件（目标）路径
			String path = request.getServletContext().getRealPath("/static/uploadfile/");
			//上传文件名
			String filename = file.getOriginalFilename();
			//String fileType = originalFileName.substring(originalFileName.indexOf(".") + 1);//截取文件拓展名.jpg
			persistFileUrl = "static/uploadfile/"+filename;//持久化路径
		    File filepath = new File(path,filename);
			//判断路径是否存在，如果不存在就创建一个
	        if (!filepath.getParentFile().exists()) { 
	        	filepath.getParentFile().mkdirs();
	        }
	        //将上传文件保存到一个目标文件当中
			file.transferTo(new File(path + File.separator + filename));
			
		}
		
		
		//int total = productService.size();
		ModelAndView mv = new ModelAndView();
		Product product = new Product();
		//product.setPRODUCT_ID(total+1);
		product.setPRODUCT_NAME(name);
		product.setPRODUCT_CONTENT(content);
		product.setMODIFY_TIME(new Date());
		product.setPRODUCT_IMG(persistFileUrl);//设置图片路径持久化
		productService.save(product);
		mv.setViewName("redirect:list.do");
		return mv;
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public ModelAndView delete(@RequestParam(value="id")Integer id) throws Exception{
		ModelAndView mv = new ModelAndView();
		productService.delete(id);
		mv.setViewName("redirect:list.do");
		return mv;
	}
	/**
	 * 
	 * 批量删除
	 * @param request
	 * @param response
	 */
	@RequestMapping("/del")  
	public void batchDeletes(HttpServletRequest request, HttpServletResponse response) {  
	    String items = request.getParameter("delitems");
	    System.out.println(items);  
	    String[] strs = items.split(",");  
	  
	    for (int i = 0; i < strs.length; i++) {  
	        try {  
	            int a = Integer.parseInt(strs[i]);  
	            productService.delete(a);  
	        } catch (Exception e) {  
	        }  
	    }  
	}  
	
}
